package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    /***
     * @function 参数校验
     * @Author sunxuJ
     */
    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        //验证是否存在该uid的订单
        Long userId = createOrderContext.getUserId();
        Example example = new Example(Order.class);
        /*example.createCriteria().andEqualTo("userId",userId)

                .andEqualTo("status",0);
        List<Order> orders = orderMapper.selectByExample(example);
        if (orders.size() == 0) {

            throw new BizException(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode(),SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage());
            //return false;
        }*/

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            @NotNull @Min(0) Long itemId = cartProductDto.getProductId();
            Stock stock = stockMapper.selectByPrimaryKey(itemId);
            if (stock==null) {
                throw new BizException(OrderRetCode.UNDERSTOCK.getCode(),
                        OrderRetCode.UNDERSTOCK.getMessage());
            }
            if(stock.getStockCount()<cartProductDto.getProductNum()){
                throw new BizException(OrderRetCode.UNDERSTOCK.getCode(),
                        OrderRetCode.UNDERSTOCK.getMessage());
            }
            if(stock.getRestrictCount()<cartProductDto.getProductNum()){
                throw new BizException(OrderRetCode.EXCEEDING_PURCHASE_LIMIT.getCode(),
                        OrderRetCode.EXCEEDING_PURCHASE_LIMIT.getMessage());

            }
        }

        return true;
    }
}
